package com.geostar.gmp.snmp;

import java.io.IOException;
import java.util.Vector;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.SnmpConstants;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;


public class SnmpSet {

     private Snmp snmp = null;
     private Address targetAddress = null;

     public static void main(String[] args) {
         try {
         	    String oidString="1.3.6.1.2.1.25.2.1.2";
         	    SnmpSet util = new SnmpSet();
                util.initComm();
                util.getPDU(oidString);
                util.setPDU(oidString);
                util.getPDU(oidString);
         } catch (IOException e) {
                e.printStackTrace();
         }
     }

     public void initComm() throws IOException {
     	 String targetAddr="udp:127.0.0.1/161";
     	 targetAddress = GenericAddress.parse(targetAddr);   
         TransportMapping transport = new DefaultUdpTransportMapping();   
         snmp = new Snmp(transport);   
         transport.listen();//监听
     }

     public ResponseEvent sendPDU(PDU pdu) throws IOException {
         // 设置 target
    	 CommunityTarget target = new CommunityTarget();//agent对象     
         target.setCommunity(new OctetString("public"));//设置共同体名   
         target.setAddress(targetAddress);//设置目标Agent地址   
         target.setVersion(SnmpConstants.version2c);//版本   
         target.setRetries(1);//重试次数   
         target.setTimeout(2000);//超时设置
        // 向Agent发送PDU，并返回Response
        return snmp.send(pdu, target);
     }

     public void setPDU(String oidString) throws IOException {
            // set PDU
            PDU pdu = new PDU();
            pdu.add(new VariableBinding(new OID(oidString)));
            pdu.setType(PDU.SET);
            sendPDU(pdu);
     }

     public void getPDU(String oidString) throws IOException {
            // get PDU
            PDU pdu = new PDU();
            pdu.add(new VariableBinding(new OID(oidString)));
            pdu.setType(PDU.GET);
            readResponse(sendPDU(pdu));
     }

     public void readResponse(ResponseEvent respEvnt) {
            // 解析Response
            if (respEvnt != null && respEvnt.getResponse() != null) {
                   Vector<VariableBinding> recVBs = (Vector<VariableBinding>) respEvnt.getResponse().getVariableBindings();
                   for (int i = 0; i < recVBs.size(); i++) {
                          VariableBinding recVB = recVBs.elementAt(i);
                          System.out.println(recVB.getOid() + " = " + recVB.getVariable());
                   }
            }
     }

}
